from fastapi import APIRouter, Depends, Query
from sqlmodel import Session
from typing import Union, List, Optional, Tuple
from crud.scales import scale as scale_crud
from crud.scales import scaledetail as scaledetail_crud
from common import response_code
import models
from dependencies import engine, SessionDep
from typing import Annotated
from routers.auth import get_current_sys_user,get_current_patient_user,get_current_doctor_user

router = APIRouter()


"""查询拥有权限量表套餐/基础量表（公共量表和当前用户组织下的量表）

Keyword arguments:
offset -- 起始位置
limit -- 每页数量
name -- 量表名称
type -- 量表类型
status -- 量表状态
is_push -- 量表推送状态
user -- 当前用户
Return: response -- 响应体
"""


@router.get(
    "/api/scale/",
    tags=["量表管理"],
    summary="查询拥有权限量表套餐/基础量表（公共量表和当前用户组织下的量表）",
    response_model=models.RespJsonScale,
)
async def get_scale(
    offset: int = 0,
    limit: int = 20,
    name: str | None = None,
    type: int | None = None,
    is_push: bool | None = None,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonScale = Depends(response_code.RespSuccessJson.resp_200),
):
    # 查询量表列表数据
    content = scale_crud.get_scale(
        offset, limit, name, type, is_push, user, session)

    # 响应体
    response.data = {
        "total": content[1],
        "totalPages": content[1] // limit + 1 if content[1] % limit else content[1] // limit,
        "items": [dict(item) for item in content[0]] if content[0] else [],
    }
    response.msg = "查询成功"

    return response


"""新增量表（基础量表/量表套餐）

Keyword arguments:
scale -- 新增量表数据
user -- 当前用户
Return: response -- 响应体
"""


@router.post(
    "/api/scale/",
    tags=["量表管理"],
    summary="新增量表（基础量表/量表套餐）",
    response_model=models.RespJsonScale,
)
async def create_scale(
    scale: models.ScaleCreate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonScale = Depends(response_code.RespSuccessJson.resp_201),
):

    # 新增量表数据
    scale_crud.create_scale(scale, user, session)

    return response


"""编辑量表（基础量表/量表套餐）

Keyword arguments:
id -- 量表id
scale -- 编辑量表数据
Return: response -- 响应体
"""


@router.put(
    "/api/scale/{id}",
    tags=["量表管理"],
    summary="编辑量表（基础量表/量表套餐）",
    response_model=models.RespJsonScale,
)
async def update_scale(
    id: int,
    scale: models.ScaleUpdate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonScale = Depends(response_code.RespSuccessJson.resp_202),
):
    # 编辑量表
    scale_crud.update_scale(id, scale, user, session)

    return response


"""删除量表（基础量表/量表套餐）

Keyword arguments:
id -- 量表id
Return: response -- 响应体
"""


@router.delete(
    "/api/scale/{id}",
    tags=["量表管理"],
    summary="删除量表（基础量表/量表套餐）",
    response_model=models.RespJsonScale,
)
async def delete_scale(
    id: int,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonScale = Depends(response_code.RespSuccessJson.resp_204),
):
    # 删除量表
    scale_crud.delete_scale(id, user, session)

    return response


"""查询量表配置的草稿数据

Keyword arguments:
id -- 量表id
Return: response -- 响应体
"""
@router.get(
    "/api/scale/draft/{id}",
    tags=["量表管理"],
    summary="查询量表配置的草稿数据",
    response_model=models.RespJsonScaleConfigDraft,
)
async def get_scale_draft(
    id: int,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonScaleConfigDraft = Depends(
        response_code.RespSuccessJson.resp_200
    ),
):
    # 查询量表配置的草稿数据
    scale_draft = scale_crud.get_scale_draft(id, user, session)

    # 响应体
    response.data = scale_draft

    return response


"""保存量表配置草稿

Keyword arguments:
id -- 量表id
scale_draft -- 量表配置草稿数据
Return: response -- 响应体
"""
@router.post(
    "/api/scale/draft/{id}",
    tags=["量表管理"],
    summary="保存量表配置草稿",
    response_model=models.RespJsonScaleConfigDraft,
)
async def save_scale_draft(
    id: int,
    scale_draft: models.ScaleConfigDraftCreate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonScaleConfigDraft = Depends(
        response_code.RespSuccessJson.resp_201
    ),
):
    scale_config_draf = scale_crud.save_scale_draft(id, scale_draft, user, session)
    # 响应体
    response.data = scale_config_draf
    response.msg = "保存成功"
    return response



"""量表推送

Keyword arguments:
scale_detail_id -- 量表id
Return: response -- 响应体
"""


@router.post(
    "/api/scale/push/{scale_id}",
    tags=["量表评估"],
    summary="量表推送",
    response_model=models.RespJsonScalePush,
)
async def scale_push(
    scale_id: int,
    user: Annotated[models.Doctor, Depends(get_current_doctor_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonScalePush = Depends(
        response_code.RespSuccessJson.resp_201
    ),
):
    # 推送量表
    scale_push = scale_crud.scale_push(scale_id, user, session)

    response.msg = "推送成功"  # 修改返回提示语：推送成功
    response.data = scale_push  # 返回推送记录

    return response


"""量表评估（获取下一题）

Keyword arguments:
url -- 量表推送链接url（路由）
curent_ques_id -- 当前题目id
answer -- 当前题目答案
Return: response -- 响应体
"""


@router.post("/api/scale/answer/next/{url}", tags=["量表评估"], summary="量表评估（获取下一题）", response_model=models.RespJsonScaleDetailQues)
async def get_scale_next_question(
    url: str,
    curent_ques_id: int | None = None,
    answers: models.ScaleAnswer | None = None,
    user: Annotated[models.Doctor, Depends(get_current_doctor_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonScaleDetailQues = Depends(
        response_code.RespSuccessJson.resp_200
    ),
):
    # 获取下一题内容
    next_question = scale_crud.get_scale_next_question(
        url, curent_ques_id, answers, session)


    # 响应体
    response.data = next_question


    return response

